<template>
    <div>
        <el-card class="box-card" style="min-height: 800px">
            <div slot="header" class="clearfix">

                <div class="media-display">
                    <el-link :underline="false" style="font-size: 20px">用户列表</el-link>
                    <el-divider direction="vertical"></el-divider>
                    <el-link :underline="false" style="font-size: 20px">要查询的角色：</el-link>
                    <el-button :type="roles.role_super ? 'warning' : 'info'" plain @click="choice($event.target,'super')">super</el-button>
                    <el-button :type="roles.role_admin ? 'primary' : 'info'" plain @click="choice($event.target,'admin')">admin</el-button>
                    <el-button :type="roles.role_user ? 'success' : 'info'" plain @click="choice($event.target,'user')">user</el-button>

                    <el-button icon="el-icon-search" circle @click="searchRoles(1)"></el-button>
                </div>
                <div style="margin-left: auto">
                    <el-input style="width: 300px"
                              clearable
                              v-model="keyWord"
                              placeholder="输入关键字搜索"/>
                    <el-button style="margin-left: 10px" type="success" plain @click="search(1)">搜索</el-button>

                    <el-button style="margin-left: 10px" type="primary" plain @click="viewAll">全部用户</el-button>
                </div>
            </div>
            <div class="text">
                <el-table
                        highlight-current-row
                        :data="tableData.list"
                        style="width: 100%">
                    <!--展开行-->
                    <el-table-column type="expand">
                        <template slot-scope="props">
                            <el-form label-position="left" inline class="demo-table-expand">
                                <el-form-item label="用户 ID">
                                    <span>{{ props.row.user_id }}</span>
                                </el-form-item>
                                <el-form-item label="用户角色">
                                    <el-tag style="cursor: pointer"
                                            :type="props.row.role_name === 'super' ? 'warning': (props.row.role_name === 'admin' ? 'primary' : 'success')">
                                        <span>{{ props.row.role_name }}</span>
                                    </el-tag>
                                </el-form-item>
                                <el-form-item label="用户账号">
                                    <span>{{ props.row.username }}</span>
                                </el-form-item>
                                <el-form-item label="电话">
                                    <span v-if="props.row.phone===undefined">暂无</span>
                                    <span v-else>{{ props.row.phone }}</span>
                                </el-form-item>
                                <el-form-item label="密码">
                                    <span>{{ props.row.password }}</span>
                                </el-form-item>
                                <el-form-item label="邮箱">
                                    <span v-if="props.row.email===undefined">暂无</span>
                                    <span v-else>{{ props.row.email }}</span>
                                </el-form-item>
                            </el-form>
                        </template>
                    </el-table-column>
                    <el-table-column
                            type="index"
                            :index="(this.tableData.currentPage-1)*this.tableData.pageSize + 1"
                            width="50">
                    </el-table-column>
                    <el-table-column
                            width="200"
                            label="用户 ID"
                            prop="user_id">
                    </el-table-column>
                    <el-table-column
                            width="200"
                            label="用户账号"
                            prop="username">
                    </el-table-column>
                    <el-table-column
                            width="200"
                            label="姓名"
                            prop="name">
                    </el-table-column>
                    <el-table-column
                            width="100"
                            label="角色"
                            prop="role_name">
                        <template slot-scope="scope">
                            <el-popover trigger="hover" placement="top" :open-delay="200">
                                <span v-if="scope.row.role_name==='super'">这是超级管理员，拥有所有权限</span>
                                <span v-else-if="scope.row.role_name==='admin'">这是管理员，拥有部分权限</span>
                                <span v-else>这是普通用户，拥有一般权限</span>
                                <div slot="reference" class="name-wrapper" >
                                    <el-tag style="cursor: pointer;width: 60px;text-align: center"
                                            :type="scope.row.role_name === 'super' ? 'warning': (scope.row.role_name === 'admin' ? 'primary' : 'success')">
                                        <span>{{ scope.row.role_name }}</span>
                                    </el-tag>
                                </div>
                            </el-popover>

                        </template>
                    </el-table-column>
                    <el-table-column
                            width="200"
                            align="center"
                            label="状态(锁定/正常)">
                        <template slot-scope="scope" >
                            <el-popconfirm
                                    :class="scope.row.role_name === 'super'? 'switch-disabled' : ''"
                                    :disabled="scope.row.role_name === 'super'"
                                    confirm-but ton-text='好的'
                                    cancel-button-text='不用了'
                                    icon="el-icon-info"
                                    icon-color="red"
                                    title="是否更改用户状态？" @confirm="updateState(scope.$index,scope.row.user_id)">
                                <el-switch
                                        slot="reference"
                                        disabled
                                        v-model="scope.row.state"
                                        :active-value="true"
                                        :inactive-value="false">
                                </el-switch>
                            </el-popconfirm>
                        </template>
                    </el-table-column>

                    <el-table-column
                            label="操作">
                        <template slot-scope="scope">
                            <el-button size="small" type="primary" @click="getInfo(scope.$index,scope.row.user_id)">修改</el-button>
                            <el-button slot="reference" size="small" type="danger" :disabled="scope.row.role_name === 'super'" @click="open()">删除</el-button>
                        </template>

                    </el-table-column>
                </el-table>

                <!--分页-->
                <el-pagination class="nav-fenye"
                               @current-change="handleCurrentChange"
                               :current-page="this.tableData.currentPage"
                               :page-size="this.tableData.pageSize"
                               layout="total, prev, pager, next, jumper"
                               :total="this.tableData.total">
                </el-pagination>
            </div>
        </el-card>

        <el-dialog
                width="30%"
                title="修改信息"
                :visible.sync="modifyAllInfoDialog"
                :before-close="handleClose">
            <div v-loading="dialogLoading" element-loading-text="拼命加载中" element-loading-body="true">
                <el-form :model="modifyAllInfoForm" :rules="rules" ref="modifyAllInfoForm" style="width: 80%" label-width="100px">
                    <el-form-item label="角色" prop="role_name">
                        <template>
                            <el-select v-model="modifyAllInfoForm.role_id" placeholder="请选择">
                                <el-option
                                        v-for="item in roleArr"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                    <span style="float: left">{{ item.label }}</span>
                                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.describe }}</span>
                                </el-option>
                            </el-select>
                        </template>
                    </el-form-item>
                    <el-form-item label="用户id" prop="user_id">
                        <el-input v-model="modifyAllInfoForm.user_id" disabled prefix-icon="el-icon-user-solid"></el-input>
                    </el-form-item>
                    <el-form-item label="账号" prop="username">
                        <el-input v-model="modifyAllInfoForm.username" disabled prefix-icon="el-icon-user-solid"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="modifyAllInfoForm.password" prefix-icon="el-icon-user-solid"></el-input>
                    </el-form-item>
                    <el-form-item label="状态" prop="state">
                        <el-switch
                                v-model="modifyAllInfoForm.state"
                                active-text="正常"
                                inactive-text="封禁">
                        </el-switch>
                    </el-form-item>
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="modifyAllInfoForm.name" prefix-icon="el-icon-user-solid"></el-input>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="modifyAllInfoForm.email" prefix-icon="el-icon-platform-eleme"></el-input>
                    </el-form-item>
                    <el-form-item label="手机" prop="phone">
                        <el-input v-model="modifyAllInfoForm.phone" prefix-icon="el-icon-phone-outline"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="modifyAllInfoDialog = false">取 消</el-button>
                <el-popconfirm
                        style="margin-left: 10px"
                        confirm-but ton-text='好的'
                        cancel-button-text='不用了'
                        icon="el-icon-info"
                        icon-color="red"
                        title="是否修改用户信息？" @confirm="submitForm('modifyAllInfoForm')">
                    <el-button type="primary" slot="reference">确 定</el-button>
                </el-popconfirm>

            </div>
        </el-dialog>


    </div>
</template>


<script>
    import MyDialog from "@components/common/MyDialog";
    export default {
        name: "UserRole",
        components: {MyDialog},
        data(){
            return{
                dialogLoading: true,
                modifyAllInfoDialog: false,
                modifyAllInfoForm:{
                    user_id: "",
                    username: "",
                    password: "",
                    state: true,
                    name: "",
                    email: "",
                    phone: "",
                    role_id: 1,
                },
                rules: {//修改密码验证规则
                    password: [
                        { required: true, message: '请输入原密码', trigger: 'blur' },
                        { min: 3, message: '长度不小于 3 个字符 ', trigger: 'blur' }
                    ],
                    state: [
                        { required: true, message: '请输入姓名', trigger: 'blur' },
                    ],
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' },
                    ],
                    email: [
                        { required: true, message: '请输入电子邮箱', trigger: 'blur' },
                    ],
                    phone: [
                        { required: true, message: '请输入电话号码', trigger: 'blur' },
                    ],
                },
                roleArr: [{
                    describe: '超级管理员',
                    value: 1,
                    label: 'super'
                }, {
                    describe: '普通管理员',
                    value: 2,
                    label: 'admin'
                }, {
                    describe: '用户',
                    value: 3,
                    label: 'user'
                }],
                globalIndex : 0,

                tableData : {},
                keyWord : '',
                roles: {//存放要搜索的角色id
                    role_super: true,
                    role_admin: true,
                    role_user: true,
                },
            }
        },
        methods : {
            open(){
                this.$confirm(`此操作将验证, 是否继续？`, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
            },
            submitForm(formName) {//
                if (formName === "modifyAllInfoForm" && this.loading) {
                    //如果是修改信息表单要先查询，等待loading状态结束
                    console.log("还在加载中")
                    return;
                }
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.modifyAllInfoForm.state = Number(this.modifyAllInfoForm.state);
                        console.log(this.modifyAllInfoForm)
                        this.$axios({
                            method : "POST",
                            url:"/admin?method=updateAllInfo",
                            data: {
                                modifyAllInfoForm : this.modifyAllInfoForm
                            },
                        }).then((response)=>{
                            console.log(response.data);
                            if (response.data === true){
                                this.$notify.success({title: '成功', message: '修改成功'});
                                //实时更新角色
                                let newRoleName = this.modifyAllInfoForm.role_id === 1 ? 'super' : (this.modifyAllInfoForm.role_id === 2 ? 'admin' : 'user')
                                //console.log("newRoleName =",newRoleName,"globalIndex =",this.globalIndex)
                                this.$set(this.tableData.list[this.globalIndex], 'role_name', newRoleName)
                                this.modifyAllInfoDialog = false;//关闭dialog
                            }else {
                                this.$notify.warning({title: '失败', message: '修改失败'});
                            }
                        }).catch((error)=> {
                            this.$notify.error({title: '失败', message: 'updateAllInfo接口错误'});
                        });
                    } else {
                        this.$notify.error({title: '错误', message: '验证不通过'});
                    }
                });
            },
            getInfo(index,user_id){
                console.log(index, user_id)
                this.globalIndex = index;
                this.modifyAllInfoDialog = true;//打开修改信息的弹窗
                this.dialogLoading = true;//进入加载
                this.$axios({//根据用户id查询个人信息
                    method : "GET",
                    url:"/admin",
                    params: {
                        method : 'queryUserAllInfo',
                        user_id : user_id,
                    }
                }).then((response)=>{
                    console.log(response.data)
                    if (response.data !== null){//如果结果不为null
                        this.modifyAllInfoForm = response.data;//显示信息
                        this.dialogLoading = false;//取消加载
                    }else{
                        this.$notify({title: '错误', message: '查询失败', type: 'error'});
                    }
                }).catch((error)=> {
                    this.$notify({title: '错误', message: 'queryUserAllInfo接口错误' + error, type: 'error'});
                });
            },
            initData(page){//初始化数据
                this.$axios({
                    method : "GET",
                    url:"/admin?method=list&currentPage=" + page,
                }).then((response)=>{
                    console.log(response.data);
                    this.tableData = response.data;
                }).catch((error)=> {
                    console.log(error);
                });
            },
            viewAll(){//查看全部用户
                this.keyWord = ""
                this.roles = Object.assign({}, this.roles, { role_super: true,role_admin: true,role_user: true })
                this.initData(1);
            },
            choice(event, role_name){
                if (role_name === "super"){
                    this.roles.role_super = !this.roles.role_super;
                }else if (role_name === "admin"){
                    this.roles.role_admin = !this.roles.role_admin;
                }else if (role_name === "user"){
                    this.roles.role_user = !this.roles.role_user;
                }

                if(event.nodeName === 'SPAN' || event.nodeName === 'I'){
                    event = event.parentNode;
                }
                event.blur();
            },
            searchRoles(page){
                console.log(Object.values(this.roles))
                let result = Object.values(this.roles).includes(true)
                //console.log(result)
                if (result){
                    //重置关键字
                    this.keyWord = '';
                    this.$axios({
                        method : "POST",
                        url:"/admin?method=queryUserByRoleId",
                        data: {
                            roles: this.roles,
                            currentPage: page,
                        }
                    }).then((response)=>{
                        console.log("response.data =",response.data)
                        if (response.data !== null){
                            this.tableData = response.data;
                        }else {
                            this.$message.warning({message: '查询角色失败' ,offset: 150});
                        }
                    }).catch((error)=> {
                        this.$message.error({message: '查询角色接口错误' + error ,offset: 150});
                    });
                }else {
                    this.$message.warning({message: '必须至少选择一个角色',offset: 150});
                }
            },

            updateState(index ,id){
                console.log(index,id)
                this.$axios({
                    method : "GET",
                    url:"/admin",
                    params: {
                        method: "updateState",
                        user_id: id,
                        state: Number(!this.tableData.list[index].state),
                    }
                }).then((response)=>{
                    if (response.data === true){
                        this.$notify.success({title: '成功', message: '修改状态成功'});
                        this.tableData.list[index].state = !this.tableData.list[index].state
                    }else {
                        this.$notify.warning({title: '错误',message: '修改状态失败'});
                    }
                }).catch((error)=> {
                    this.$notify.error({title: '错误',message: 'updateState接口错误' + error});
                });
            },
            search(page){//关键字搜索
                if (this.keyWord === ""){
                    this.$message.warning({showClose: true, message:'搜索关键字不能为空', offset:80});return
                }
                //重置角色
                this.roles = Object.assign({}, this.roles, { role_super: true,role_admin: true,role_user: true })
                this.$axios({
                    method : "post",
                    url:"/admin?method=search",
                    data : {
                        keyWord : this.keyWord,
                        currentPage : page
                    },
                }).then((response)=>{
                    if (response.data !== null){
                        console.log(response.data);
                        this.tableData = response.data
                    }else{
                        this.$message.warning({showClose: true, message:'没有找到你要搜索的数据，请尝试更改搜索条件', offset:80});
                    }
                }).catch((error)=> {
                    this.$message.warning({showClose: true, message: "用户名搜索接口错误", offset:80});
                });
            },
            handleCurrentChange(currentPage){//处理分页数据
                console.log("handleCurrentChange =",Object.values(this.roles).includes(false));
                if (this.keyWord !== ""){
                    //如果有关键字，就走关键字分页
                    this.search(currentPage);
                }else if(Object.values(this.roles).includes(false)){
                    //如果角色有被筛选，就走角色分页
                    this.searchRoles(currentPage)
                }else {
                    //什么都没有，走正常分页
                    this.initData(currentPage)
                }
            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {});
            },
        },
        beforeMount (){//初始化数据
            this.initData(1)
        },
        mounted(){
        },
    }
</script>

<style scoped>


    @media (max-width: 1100px){
        .media-display{
            display: none;
        }
    }
    .el-form{
        width: auto;
    }
    *{
        outline: none;
    }

    .el-card__header{
        background-color: rgba(0,0,0,.03);
    }
    .el-card__body{
        padding-top: 0;
    }
    .clearfix{
        display: flex;
        align-items: center;
    }
    .text {
        font-size: 14px;
    }
    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    .clearfix:after {
        clear: both
    }

    tr{
        height: 60px;
    }
    .demo-table-expand {
        font-size: 0;
    }
    >>> .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }
    .el-form--inline .el-form-item__content{
        vertical-align: baseline;
    }
    .el-switch__label{
        color: #909399;
    }

    /*重写switch的disabled时css*/
    >>>.el-switch.is-disabled{
        opacity: 1;
    }
    >>>.el-switch.is-disabled .el-switch__core, .el-switch.is-disabled .el-switch__label{
        cursor: pointer;
    }

    .switch-disabled{
        cursor: no-drop;
    }
</style>
